<template>
  <!--  班组-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="班组名称">
          <el-input v-model="searchParam.name" placeholder="请输入班组名称" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button type="primary" :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 350px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize
              + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="code" label="班组编号" align="center" min-width="250"/>
        <el-table-column prop="name" label="班组名称" align="center" min-width="250"/>
        <el-table-column prop="userName" label="班组长" align="center" min-width="250"/>
        <el-table-column prop="description" label="班组描述" align="center" min-width="200"/>
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small" plain
                       :icon="Edit">编辑
            </el-button>
            <el-button @click="handleDel(scope.row)" text type="danger" size="small"
                       :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="800" top="5vh">
      <el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item required label="工厂" prop="organizationId">
              <el-tree-select v-model="formData.organizationId" :data="workRoomList" check-strictly
                              :props="{ children: 'treeList', label: 'name', value: 'id' }" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="班组名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入班组名称" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="班组编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入班组编码" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="班组成员" prop="ids">
              <el-select v-model="formData.ids" placeholder="请选择班组成员" multiple clearable filterable
                         style="width: 300px">
                <el-option v-for="item in userList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="班组长" prop="headerId">
              <el-select v-model="formData.headerId" placeholder="请选择班组长" clearable filterable
                         style="width: 300px">
                <el-option v-for="item in userList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="班组描述">
              <el-input type="textarea" v-model="formData.description" placeholder="请输入班组描述" clearable
                        style="width:725px "></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useEquipmentData} from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
  DocumentCopy,
  LocationFilled
} from '@element-plus/icons-vue';


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
  console.log(e, 'handleClick');
};

const rowInfo = ref({});


const workOrderList = ref({});

const showMaterial = ref(false);

const workDetailData = ref([{
  code: '1code89980',
  name: '测试name',
  qualityType: 'qualityType'
}]);

const workOrderChange = (e) => {
  if (!e) {
    formData.count = null;
    return false;
  }
  axiosInstance.post('/api/workOrder/queryByWorkId', {id: e})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        formData.count = res.data.orderCount;
        formData.materialId = res.data.materialId;
        formData.productId = res.data.productId;
      });
};

const addWorkOrderDetail = () => {
  workDetailData.value.push({});
};


const delWorkOrderDetail = (e) => {
  workDetailData.value.splice(e, 1);
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  qualityNumber: 1,
  qualityType: '',
  qualityInterval: 1,
  qualityIsLive: true,
  qualityRemark: ''
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  organizationId: [
    {required: true, message: '请选择车间/产线', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入班组名称', trigger: 'blur'}
  ],
  ids: [
    {required: true, message: '请选择班组人员', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入班组编码', trigger: 'blur'}
  ],
  headerId: [
    {required: true, message: '请选择班组长', trigger: 'blur'}
  ]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

const materiaList = ref([]);//物料表
const userList = ref([]);//人员
const workRoomList = ref([]);//车间
const procedureOrderList = ref([]);//工序订单

const getOption = () => {
  axiosInstance.post('/api/auth/user/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        userList.value = res.data;
      });

  axiosInstance.get('/api/basedata/factoryModel/getTreeList/1', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};


// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/basedata/team/getPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  // ruleFormRef.value.resetFields()
  formData = reactive({});
  showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  const list = JSON.parse(JSON.stringify(row));
  const ids = []

  // for (const item of list.teamUserDTOS) {
  // 	ids.push(item.id)
  // }
  // list.ids = ids
  Object.assign(formData, list);
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete('/api/basedata/team/delete', {id: row.id}).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      const teamUserDTOS = []
      userList.value.forEach(user => {
        if (formData.ids.includes(user.id))
          teamUserDTOS.push(user)
      })
      formData.teamUserDTOS = teamUserDTOS
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/basedata/team/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // formData.teamUserDTOS = {
        // 	headerId: formData.teamUser
        // };
        // 新建
        axiosInstance.post('/api/basedata/team/save', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


onMounted(() => {
  getList();
  getOption();
});

</script>
<style scoped>
.content {
}
</style>
